package com.yjd.comm.fundservice.util;

import com.alibaba.fastjson.JSON;
import com.yjd.comm.bank.model.BankModel;
import com.yjd.comm.enums.RepaymentTypeEnum;
import com.yjd.comm.enums.TimeUnit;
import com.yjd.comm.fundservice.dto.*;
import com.yjd.comm.fundservice.enums.BusTypeEnum;
import com.yjd.comm.order.model.OrderModel;
import com.yjd.comm.org.model.OrganizationModel;
import com.yjd.comm.user.dto.ContactInfo;
import com.yjd.comm.user.dto.ResidenceInfo;
import com.yjd.comm.user.dto.WorkInfo;
import com.yjd.comm.user.model.UserDataModel;
import com.yjd.comm.user.util.UserUtil;
import com.yjd.comm.util.ServletUtil;

import java.util.List;

/**
 * 乾康接口对接服务
 * Created by yjd-wap on 2018/1/21.
 */
public class QianKangServer {

    /**
     * 借款申请
     * @param org 机构信息
     * @param order 订单信息
     * @param userData 借款用户信息
     * @param bank 借款用户银行信息
     * @return
     * @throws Exception
     */
    public static QKLoanApplyResponse loanApply(OrganizationModel org, OrderModel order, UserDataModel userData, BankModel bank) throws Exception {

        // 贷款申请需要的信息
        QKLoanApplyModel applyModel = buildLoanApplyModel(org, order, userData, bank);

        // 贷款申请的响应信息
        QKLoanApplyResponse response = QianKangServerUtil.sendMsg(applyModel, "url", BusTypeEnum.BUS_TYPE_1, "bus_id", QKLoanApplyResponse.class);

        return response;
    }

    private static QKLoanApplyModel buildLoanApplyModel(
            OrganizationModel org, OrderModel order, UserDataModel userData, BankModel bank){

        QKLoanApplyModel request = new QKLoanApplyModel();
        request.setAgent_id(order.getOrg_id().toString());
        request.setAgent_order_id(order.getOrder_no());
        request.setLoan_amount((int)(order.getLoan_amount()*100));
        request.setLoan_rate(order.getLoan_rate());
        request.setLoan_rate_unit(TimeUnit.YEAR.getLabel());
        request.setLoad_period(order.getPeriod());
        request.setLoan_period_unit(TimeUnit.MONTH.getLabel());
        request.setRepayment_way(RepaymentTypeEnum.TYPE_3.getCode());
        request.setStart_date(""); // optional
        request.setEnd_date(""); // optional
        request.setProduct_name(""); // optional
        request.setProduct_desc(""); // optional
        request.setPayee_bank_account(org.getPayee_bank_account());
        request.setPayee_bank_card(org.getPayee_bank_card());
        request.setBorrower_name(bank.getId_name());
        request.setBorrower_id(bank.getId_number());
        request.setBorrower_contact(bank.getBank_mobile().toString());
        request.setBorrower_bank_code(2); //TODO
        request.setBorrower_bank_card(bank.getBank_card_number());

        // 借款人单位信息
        WorkInfo workInfo = JSON.parseObject(userData.getJob_info(), WorkInfo.class);
        if( !UserUtil.isJobInfoCompleted(workInfo) ){
            throw new IllegalArgumentException("借款人工作单位信息不完整");
        }
        request.setBorrower_work_name(workInfo.getCompany());
        request.setBorrower_work_address(workInfo.getCompanyLocation());

        // 借款人居住信息
        ResidenceInfo rdnInfo = JSON.parseObject(userData.getResidence(), ResidenceInfo.class);
        if( !UserUtil.isResidenceInfoCompleted(rdnInfo) ){
            throw new IllegalArgumentException("借款人居住信息不完整");
        }
        request.setBorrower_address(rdnInfo.getCurrentResidenceAddr().getFullAddress());
        request.setBorrower_home_address(rdnInfo.getFamilyAddr().getFullAddress());
        request.setBorrower_census_address(rdnInfo.getDomicileAddr().getFullAddress());

        // 借款人紧急联系人信息
        List<ContactInfo> contactInfos = JSON.parseArray(userData.getUrgent_contacts(), ContactInfo.class);
        if( !UserUtil.isUrgentContactInfoCompleted(contactInfos) ){
            throw new IllegalArgumentException("借款人紧急联系人信息不完整");
        }
        request.setBorrower_contact_first_name(contactInfos.get(0).getIdName());
        request.setBorrower_contact_first_phone(contactInfos.get(0).getMobile_number());
        request.setBorrower_contact_first_relation(contactInfos.get(0).getRelation());
        request.setBorrower_contact_second_name(contactInfos.get(1).getIdName());
        request.setBorrower_contact_second_phone(contactInfos.get(1).getMobile_number());
        request.setBorrower_contact_second_relation(contactInfos.get(1).getRelation());

        request.setCallback_url(ServletUtil.getRootPath() + "/qk/callback/callback");

        return request;
    }

    /**
     * 查询还款计划
     * @param org_id 机构id
     * @param order_no 订单编号
     * @param period 还款期数（默认：0 则查询全部期数的计划列表）
     * @return
     * @throws Exception
     */
    public static QKRepaymentPlanModel queryRepaymentPlan(Long org_id, String order_no, int period) throws Exception {

        // 查询还款计划需要的信息
        QKRepaymentApplyModel request = new QKRepaymentApplyModel();
        request.setAgent_id(org_id.toString());
        request.setAgent_order_id(order_no);
        request.setTerm_no(period);

        // 还款计划信息
        QKRepaymentPlanModel plan = QianKangServerUtil.sendMsg(request, "url", BusTypeEnum.BUS_TYPE_1, "bus_id", QKRepaymentPlanModel.class);

        return plan;
    }
}
